<template>
  <div class="security-settings">
    <van-nav-bar
      title="账号安全"
      left-arrow
      @click-left="onClickLeft"
    />

    <div class="settings-section">
      <van-cell-group>
        <van-cell
          title="手机号码"
          :value="maskPhone(userInfo.phone)"
          is-link
          @click="showUpdatePhone"
        />
        <van-cell
          title="邮箱地址"
          :value="maskEmail(userInfo.email)"
          is-link
          @click="showUpdateEmail"
        />
        <van-cell
          title="修改密码"
          is-link
          @click="showUpdatePassword"
        />
      </van-cell-group>
    </div>

    <!-- 修改手机号码弹窗 -->
    <van-dialog
      v-model:show="showPhoneDialog"
      title="修改手机号码"
      show-cancel-button
      :before-close="onDialogClose"
    >
      <div class="dialog-content">
        <van-field
          v-model="form.phone"
          label="新手机号"
          placeholder="请输入新手机号"
          :rules="[{ required: true, message: '请输入手机号' }]"
        />
        <van-field
          v-model="form.code"
          center
          label="验证码"
          placeholder="请输入验证码"
          :rules="[{ required: true, message: '请输入验证码' }]"
        >
          <template #button>
            <van-button
              size="small"
              type="primary"
              :disabled="!!countdown"
              @click="sendCode"
            >
              {{ countdown ? `${countdown}s` : '发送验证码' }}
            </van-button>
          </template>
        </van-field>
      </div>
    </van-dialog>

    <!-- 修改邮箱弹窗 -->
    <van-dialog
      v-model:show="showEmailDialog"
      title="修改邮箱地址"
      show-cancel-button
      :before-close="onDialogClose"
    >
      <div class="dialog-content">
        <van-field
          v-model="form.email"
          label="新邮箱"
          placeholder="请输入新邮箱"
          :rules="[{ required: true, message: '请输入邮箱' }]"
        />
        <van-field
          v-model="form.code"
          center
          label="验证码"
          placeholder="请输入验证码"
          :rules="[{ required: true, message: '请输入验证码' }]"
        >
          <template #button>
            <van-button
              size="small"
              type="primary"
              :disabled="!!countdown"
              @click="sendCode"
            >
              {{ countdown ? `${countdown}s` : '发送验证码' }}
            </van-button>
          </template>
        </van-field>
      </div>
    </van-dialog>

    <!-- 修改密码弹窗 -->
    <van-dialog
      v-model:show="showPasswordDialog"
      title="修改密码"
      show-cancel-button
      :before-close="onDialogClose"
    >
      <div class="dialog-content">
        <van-field
          v-model="form.oldPassword"
          label="原密码"
          type="password"
          placeholder="请输入原密码"
          :rules="[{ required: true, message: '请输入原密码' }]"
        />
        <van-field
          v-model="form.newPassword"
          label="新密码"
          type="password"
          placeholder="请输入新密码"
          :rules="[{ required: true, message: '请输入新密码' }]"
        />
        <van-field
          v-model="form.confirmPassword"
          label="确认密码"
          type="password"
          placeholder="请再次输入新密码"
          :rules="[{ required: true, message: '请确认新密码' }]"
        />
      </div>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showSuccessToast } from 'vant'

const router = useRouter()

// 用户信息
const userInfo = ref({
  phone: '13800138000',
  email: 'example@example.com'
})

// 表单数据
const form = ref({
  phone: '',
  email: '',
  code: '',
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 弹窗控制
const showPhoneDialog = ref(false)
const showEmailDialog = ref(false)
const showPasswordDialog = ref(false)
const countdown = ref(0)

// 返回上一页
const onClickLeft = () => {
  router.back()
}

// 隐藏手机号中间四位
const maskPhone = (phone) => {
  if (!phone) return ''
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// 隐藏邮箱用户名部分
const maskEmail = (email) => {
  if (!email) return ''
  const [username, domain] = email.split('@')
  const maskedUsername = username.charAt(0) + '****' + username.charAt(username.length - 1)
  return `${maskedUsername}@${domain}`
}

// 显示修改手机号弹窗
const showUpdatePhone = () => {
  form.value = { phone: '', code: '' }
  showPhoneDialog.value = true
}

// 显示修改邮箱弹窗
const showUpdateEmail = () => {
  form.value = { email: '', code: '' }
  showEmailDialog.value = true
}

// 显示修改密码弹窗
const showUpdatePassword = () => {
  form.value = { oldPassword: '', newPassword: '', confirmPassword: '' }
  showPasswordDialog.value = true
}

// 发送验证码
const sendCode = async () => {
  try {
    // TODO: 调用发送验证码接口
    // await sendVerificationCode({ phone: form.value.phone })
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
    showToast('验证码已发送')
  } catch (error) {
    console.error('发送验证码失败:', error)
    showToast('发送失败，请重试')
  }
}

// 弹窗关闭前的处理
const onDialogClose = (action) => {
  if (action === 'confirm') {
    // TODO: 根据当前打开的弹窗类型处理不同的表单提交
    if (showPhoneDialog.value) {
      return handleUpdatePhone()
    } else if (showEmailDialog.value) {
      return handleUpdateEmail()
    } else if (showPasswordDialog.value) {
      return handleUpdatePassword()
    }
  }
  return true
}

// 处理修改手机号
const handleUpdatePhone = async () => {
  try {
    // TODO: 调用修改手机号接口
    // await updatePhone(form.value)
    showSuccessToast('手机号修改成功')
    return true
  } catch (error) {
    console.error('修改手机号失败:', error)
    showToast('修改失败，请重试')
    return false
  }
}

// 处理修改邮箱
const handleUpdateEmail = async () => {
  try {
    // TODO: 调用修改邮箱接口
    // await updateEmail(form.value)
    showSuccessToast('邮箱修改成功')
    return true
  } catch (error) {
    console.error('修改邮箱失败:', error)
    showToast('修改失败，请重试')
    return false
  }
}

// 处理修改密码
const handleUpdatePassword = async () => {
  try {
    if (form.value.newPassword !== form.value.confirmPassword) {
      showToast('两次输入的密码不一致')
      return false
    }
    // TODO: 调用修改密码接口
    // await updatePassword(form.value)
    showSuccessToast('密码修改成功')
    return true
  } catch (error) {
    console.error('修改密码失败:', error)
    showToast('修改失败，请重试')
    return false
  }
}
</script>

<style lang="scss" scoped>
.security-settings {
  min-height: 100vh;
  background-color: #f7f8fa;

  .settings-section {
    margin-top: 12px;
  }

  .dialog-content {
    padding: 16px;
  }
}
</style>
